<template>
    <!-- 添加按钮 -->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>
    <!-- 修改或者添加的对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
            <el-form label-width="120px">
                <el-form-item label="规格名称">
                    <el-input v-model="productSpec.specName"/>
                </el-form-item>
                <el-form-item>
                    <el-button size="default" type="success" @click="addSpec">
                        添加新规格
                    </el-button>
                </el-form-item>
                <el-form-item label="" v-for="(item , index) in productSpec.specValue" :key="index">
                    <el-row>
                        <el-col :span="10">
                            <el-input
                                    v-model="item.key"
                                    placeholder="规格"
                                    style="width: 90%;"
                                    />
                        </el-col>
                        <el-col :span="10">
                            <el-input
                                    v-model="item.valueList"
                                    placeholder="规格值(如:白色,红色)"
                                    style="width: 90%;"
                                    />
                        </el-col>
                        <el-col :span="4">
                            <el-button size="default" type="danger" @click="delSpec(index)">删除</el-button>
                        </el-col>
                    </el-row>  
                    
                </el-form-item>
                <el-form-item align="right">
                    <el-button type="primary" @click="saveOrUpdate">提交</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


    <!-- 数据列表 -->
    <el-table :data="list" style="width: 100%">
        <el-table-column prop="specName" label="规格名称" />
        <el-table-column label="规格值" #default="scope">
        <div
            v-for="(item1, index1) in scope.row.specValue"
            :key="index1"
            style="padding: 5px; margin: 0;width: 100%;"
        >
            {{ item1.key }}：
            <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
            >
            {{ item2 }}
            </span>
        </div>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" align="center" width="200" #default="scope">
            <el-button type="primary" size="small" @click="editShow(scope.row)">
                修改
            </el-button>
            <el-button type="danger" size="small" @click="remove(scope.row.id)">
                删除
            </el-button>
        </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
               v-model:current-page="pageParams.page"
               v-model:page-size="pageParams.limit"
               :page-sizes="[10, 20, 50, 100]"
               layout="total, sizes, prev, pager, next"
               :total="total"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
            />
     
</template>
<script setup>
import { ref , onMounted } from 'vue'
import { DeleteProductSpecById,GetProductSpecPageList,SaveProductSpec,UpdateProductSpecById } from '@/api/productSpec.js'
import { ElMessage, ElMessageBox } from 'element-plus'

//删除处理
const remove=(id)=>{

    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
        //请求接口处理
      await DeleteProductSpecById(id)
      ElMessage.success('删除成功')
      fetchData()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })

}


//修改规格处理
//回显数据方法
const editShow=(row)=>{
    //赋值回显
    productSpec.value=row
    //显示对话框
    dialogVisible.value=true


}
//修改保存
const updateData=async()=>{
  //克隆数据模型--避免双向绑定的数据模型受到影响
  const productSpecClone=JSON.parse(JSON.stringify(productSpec.value))

  console.log(productSpecClone)
//"[{"key":"颜色","valueList":["白色","红色","黑色"]},{"key":"内存","valueList":["8G","18G"]}]"
//转化规格值的类型和格式
productSpecClone.specValue.forEach(item=>{
    //注意，此时修改，新添加的属性值中的valueList属性为string类型，回显的是数组类型
    if(typeof item.valueList=="string"){

        item.valueList= item.valueList.split(",")
    }


})

//转换成字符串
//[{\"key\":\"1\",\"valueList\":[\"1\",\"2\",\"3\",\"4\",\"5\"]},{\"key\":\"2\",\"valueList\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}]
productSpecClone.specValue=JSON.stringify(productSpecClone.specValue)

//请求后端数据接口
const{code} =await UpdateProductSpecById(productSpecClone)
//判断
if(code===200){
//提示
ElMessage.success("修改成功")
//隐藏
dialogVisible.value=false
//刷新
fetchData()


}
}


//新增规格处理
//定义对话框变量
const dialogVisible =ref(false)
//定义新增窗口显示的方法
const addShow=()=>{
    dialogVisible.value=true

}
//定义规格数据模型
const defaultFromParams={
    id:'',
    specName:'',
    specValue:[
        {
            key:'',
            valueList:[]
        }
    ]

}
const productSpec=ref(defaultFromParams)
//新增规格项
const addSpec=()=>{

    productSpec.value.specValue.push({})
}
//删除规格项
//索引
const delSpec=(index)=>{

    //splice(参数一，参数二) 移除指定位置的数组元素
    //参数一：开始的索引
    //参数二：移除数组元素的个数
    productSpec.value.specValue.splice(index,1)

}

//定义新增方法
const saveData= async()=>{

    //克隆数据模型--避免双向绑定的数据模型受到影响
    const productSpecClone=JSON.parse(JSON.stringify(productSpec.value))

    //"[{"key":"颜色","valueList":["白色","红色","黑色"]},{"key":"内存","valueList":["8G","18G"]}]"
    //转化规格值的类型和格式
    productSpecClone.specValue.forEach(item=>{
        item.valueList= item.valueList.split(",")

    })

    //转换成字符串
    //[{\"key\":\"1\",\"valueList\":[\"1\",\"2\",\"3\",\"4\",\"5\"]},{\"key\":\"2\",\"valueList\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}]
    productSpecClone.specValue=JSON.stringify(productSpecClone.specValue)

    //请求后端数据接口
    const{code} =await SaveProductSpec(productSpecClone)
    //判断
    if(code===200){
    //提示
    ElMessage.success("新增成功")
    //隐藏
    dialogVisible.value=false
    //刷新
    fetchData()

    }
    




    // console.log(productSpec.value)


}

//提交方法
const saveOrUpdate=()=>{
    //判断
    if(!productSpec.value.id){
        saveData()
    }else{
        updateData()
    }


}



//分页改变事件处理
const handleSizeChange=()=>{

    fetchData()
}
const handleCurrentChange=()=>{

fetchData()
}

//定义分页数据模型
const defaultPageParam={

    page:1,
    limit:10
}
const pageParams=ref(defaultPageParam)

//定义分页的总记录数
const total=ref(0)

//页面挂载后，查询数据
onMounted(()=>{
    fetchData()

})

//查询方法
const fetchData= async()=>{
    //请求查询接口
    const {data} =await GetProductSpecPageList(pageParams.value.page,pageParams.value.limit)
   
    //转化数据为数据类型
    //"specValue": "[{\"key\":\"高度\",\"valueList\":[\"200\"]},{\"key\":\"容积\",\"valueList\":[\"60L\"]}]"
    data.list.forEach(item => {

        item.specValue=JSON.parse(item.specValue)
    });

    //赋值列表
    list.value=data.list
    //赋值总记录数
    total.value=data.total


}

// 表格数据模型
const list = ref([
    {
        "id": 2,
        "createTime": "2023-05-06 12:56:08",
        "specName": "笔记本电脑",
        "specValue": [{"key":"内存","valueList":["8G","18G","32G"]}]
    },
    {
        "id": 1,
        "createTime": "2023-05-06 12:40:22",
        "specName": "小米手机",
        "specValue": [{"key":"颜色","valueList":["白色","红色","黑色"]},{"key":"内存","valueList":["8G","18G"]}]
    }
])


</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
    
.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}

</style>